// 导入 小程序 IoT 库
const Paho = require('paho-mqtt.js')

let client = null;

Page({
  data: {
    msg: ""
  },
  init: function () {
    /**
     * IoT 初始化
     */
    client = new Paho.Client('ccf5f43883f344ed92a1e5f3f2acae8b.mqtt.iot.bj.baidubce.com', 8884, "12344444444");

    client.connect({
      userName: "ccf5f43883f344ed92a1e5f3f2acae8b/amdin",
      password: "P66oRBOysrISxIVGONVAkF73EYM0+s/ldfhEWxZRVsI=",
      useSSL: true,
      keepAliveInterval: 60,
      onSuccess: function () {
        console.log('connected');
        client.subscribe("$baidu/iot/general/#", {
          qos: 1
        });
      }
    });
  },
  msg_callback: function () {
    let that = this;
    /**
     * IoT 消息回调
     */
    client.onMessageArrived = function (msg) {
      console.log(msg.topic, msg.payloadString);
      that.setData({
        msg: msg.payloadString,
      })
    }
  },
  publish_msg: function (topic, msg) {
    /**
     * IoT 发送消息
     */
    var message = new Paho.Message(msg);
    message.destinationName = topic;
    message.qos = 1;
    client.send(message);
  },
  formSubmit: function (e) {
    let msg = e.detail.value.msg;
    this.publish_msg("okf/msg/test", msg);
  },
  onLoad: function () {
    this.init();
    this.msg_callback();
    console.log("mqtt onload")
  }
})